package com.heima.wemedia.service.Impl;


import com.alibaba.fastjson.JSONArray;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.constants.admin.AdminConstants.WemediaConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void autoScanWmNews(Integer id) {
        log.info("接收到内容id为 {}", id);
        //检查参数 id
        if (id == null) {
            log.error("参数有问题");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数newid有问题");
        }
        //根据id查询wmnew文章数据
        WmNews wmNews = wmNewsMapper.selectById(id);
        //检查文章是否为空
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //如果类型不为1 未批准
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数类型应该为1");
        }
        //审核文章
        //抽取出文章的所有文本内容，所有图片内容
        Map<String, Object> contengAndImages = handleTextAndImages(wmNews);

        //DFA敏感词审核
        boolean isSensitive = handleSensitive((String) contengAndImages.get("content"), wmNews);
        if (!isSensitive) {
            return;//敏感词审核失败，直接结束方法
        }

        //阿里云文本审核
        boolean isTextScan = handleText((String) contengAndImages.get("content"), wmNews);
        if (!isTextScan) {
            return;//敏感词审核失败，直接结束方法
        }
        //阿里云图片审核
        boolean isImagesScan = handleImages((List<String>) contengAndImages.get("images"), wmNews);
        if (!isImagesScan) {
            return;//图片审核失败，直接结束方法
        }
        //审核通过了， 最后把状态改为8
        updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "审核通过");


        //延时队列 .发送消息
        long publishTime = wmNews.getPublishTime().getTime();
        long nowTime = System.currentTimeMillis();//当前时间
        long remainTime = (publishTime - nowTime);

        //发送消息
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY, wmNews.getId()
                //设置延迟属性第四个参数
                , new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {

                        //对消息做后置处理,设置消息头 x-delay
                        message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                        return message;
                    }
                }
        );
    }



    @Autowired
    GreenImageScan greenImageScan;

    //阿里云审核图片的方法
    private boolean handleImages(List<String> images, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenImageScan.imageUrlScan(images);

            //有结果
            String suggestion = (String) map.get("suggestion");

            switch (suggestion) {
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "图片中有不确定因素,转人工审核");
                    flag = false;
                    break;
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "图片中有违规内容,审核失败");
                    flag = false;
                    break;
            }


        } catch (Exception e) {
            e.printStackTrace();

            flag = false;
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用失败，转人工审核");

        }
        return flag;
    }


    @Autowired
    GreenTextScan greenTextScan;

    //调用阿里云 校验文本信息是否违规
    //如果阿里云返回为block 把文章状态改成2   review 状态设置为3   出现异常  ： 3
    private boolean handleText(String content, WmNews wmNews) {
        boolean flag = true;

        try {
            Map map = greenTextScan.greenTextScan(content);

            //有返回结果
            String suggestion = (String) map.get("suggestion");

            switch (suggestion) {
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文本中有不确定因素,转人工审核");
                    flag = false;
                    break;
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文本中有违规内容,审核失败");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "调用阿里云检查失败哦,转人工审核");
            flag = false;
        }
        return flag;
    }


    @Autowired
    AdminFeign adminFeign;

    //DFA审核敏感词
    private boolean handleSensitive(String content, WmNews wmNews) {

        ResponseResult<List<String>> sensitivesResult = adminFeign.sensitives();

        if (sensitivesResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }

        //得到敏感词
        List<String> sensitivesResultData = sensitivesResult.getData();

        //使用工具类初始化
        SensitiveWordUtil.initMap(sensitivesResultData);

        //使用DFA算法
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);

        //判断map中有敏感词，返回状态为2
        if (map != null && map.size() > 0) {
            //修改文章状态
            updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文本内容中包含自管理的敏感词");
        }

        return true;
    }

    //修改文章状态的方法
    public void updateWmNews(WmNews wmNews, Short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wmNewsMapper.updateById(wmNews);
    }


    /**
     * 抽取出文章的所有文本内容，所有图片内容
     *
     * @param wmNews 查询出的文章内容
     * @return
     */


    @Value("${file.oss.web-site}")
    String website;


    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //首先抽取文本内容（1 . 标题   2.  内容）
        Map<String, Object> result = new HashMap<>();
        String contentJson = wmNews.getContent();
        //将json装换位字符串
        List<Map> contentMap = JSONArray.parseArray(contentJson, Map.class);

        //抽取 文本内容(标题)
        StringBuilder content = new StringBuilder(wmNews.getTitle());
        contentMap.stream().filter(map -> map.get("type").equals("text"))
                .map(o -> (String) o.get("value"))
                .forEach((text) -> content.append("_hmtt_" + text));
        result.put("content", content.toString());

        //然后抽取图片内容(content中的图片  还有封面中的images的图片)
        List<String> images = contentMap.stream()
                .filter(map -> map.get("type").equals("image"))
                .map(o -> (String) o.get("value"))
                .collect(Collectors.toList());
        //封面  字符串 用，链接

        if (StringUtils.isNotBlank(wmNews.getImages())) {

            List<String> coverImages = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> website + url)
                    .collect(Collectors.toList());
            images.addAll(coverImages);
        }
        images = images.stream().distinct().collect(Collectors.toList());

        result.put("images", images);

        return result;


    }
}
